package com.kgd.news.controller.admin;

import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.kgd.news.entity.Options;
import com.kgd.news.utils.BaseController;
import com.kgd.news.utils.StringUtilsWx;

import java.util.Map;

/**
 * @Email: huangsanm@foxmail.com
 * @Date: 2017/10/8
 * @Time: 下午10:34
 */
public class OptionsController extends BaseController {

    @Override
    public void list() {
        String type = getPara("type");
        String questionid = getPara("questionid");
        if (!StringUtilsWx.isEmpty(questionid)) {
            setSessionAttr("questionid", questionid);
        }else{
            questionid = getSessionAttr("questionid");
        }
        String sql = "from options where 1 = 1";
        if (!StringUtilsWx.isEmpty(type)) {
            sql += " and type = " + type;
        }
        if (!StringUtilsWx.isEmpty(questionid)) {
            sql += " and questionid = " + questionid;
        }
        sql += " order by sort desc";
        Page<Options> data = Options.dao.paginate(getPageIndex("options"), PAGE_SIZE, "select *", sql);
        setAttr("data", data);
        render("option_list.html");
    }

    @Override
    public void edit() {
        Integer id = getParaToInt("id");
        Options res = Options.dao.findById(id);
        setAttr("option", res);
        render("option_edit.html");
    }

    @Override
    public void save() {
        Map<String, String[]> data = getParaMap();
        if(data != null && !data.isEmpty()){
            String[] items = data.get("item");
            String[] score = data.get("score");

            Options sd = getModel(Options.class, "option");
            sd.setItems(JSON.toJSONString(items));
            sd.setValues(JSON.toJSONString(score));
            sd.setQuestionid(Integer.valueOf(getSessionAttr("questionid")));
            if(sd != null && sd.getId() != null){
                sd.update();
            }else{
                sd.save();
            }
        }

        list();
    }

    @Override
    public void del() {
        String ids = getPara("ids");
        Db.update("delete from options where id in (" + ids + ")");

        list();
    }
}
